$(document).ready(function(){
     $("#btnVisualization").attr('href',"http://"+location.hostname+"/visualization");
    $("#btnVisualization").click(function(e){
       
       $(location).attr('href',"http://"+location.hostname+"/visualization");
    });
 });
 $(document).ready(function(){
 $("#btnPublication").attr('href',"http://"+location.hostname+"/publication");
    $("#btnPublication").click(function(e){

       $(location).attr('href',"http://"+location.hostname+"/publication");
    });
 });



 $(document).ready(function() {

            $(".signin").click(function(e) {
                e.preventDefault();
                $("fieldset#signin_menu").toggle();
                $(".signin").toggleClass("menu-open");
            });

            $("fieldset#signin_menu").mouseup(function() {
                return false
            });
            $(document).mouseup(function(e) {
                if($(e.target).parent("a.signin").length==0) {
                    $(".signin").removeClass("menu-open");
                    $("fieldset#signin_menu").hide();
                }
            });

        });
$(document).ready(function() {
    $.defaultText();
});

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request.responseText, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}
function parseXml(str)
{
    if (window.ActiveXObject) {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
    } else if (window.DOMParser) {
        return (new DOMParser).parseFromString(str, 'text/xml');
    }
}
function logOut()
{
 $(location).attr('href',"http://"+location.hostname+"/login/logout");

 

}


function showAsDialog(wwidth,wheight,wtop,wleft,masking,divid)
{
                    var id = "#"+divid;

		//Get the screen height and width

                var maskHeight="0px";

		var maskWidth="0px";
                    if(masking==true)
                        {
                    maskHeight=$(document).height();
                    maskWidth=$(window).width();
                        }

                        if(wwidth>0)
                        {

                            $(id).css({'width':wwidth+"px"});
                        }
                        else
                        {

                            $(id).css({'width':"300px"});
                        }
                        if(wheight>0)
                        {

                            $(id).css({'height':wheight+"px"});
                        }
                        else
                        {

                            $(id).css({'height':"250px"});
                        }


		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});

		//transition effect
		$('#mask').fadeIn(100);
		$('#mask').fadeTo("slow",0.8);

		//Get the window height and width
//		var winH = $(window).height();
//		var winW = $(window).width();


                $(id).css('top',  wtop);//winH/2-$(id).height()/2);
		$(id).css('left', wleft);//winW/2-$(id).width()/2);


		//transition effect
		$(id).fadeIn(200);
}



//function LoadUserConnectionList() {
//    $.get("http://"+location.hostname+"/redsea20_dev.php/home/ConnectionAutocomplete", {}, function(data) {
//        $( "#txtMailTo" ).autocomplete({
//            source: data.split("###"),
//            minLength: 0,
//            max: 10,
//            autoFill: true,
//            mustMatch: false,
//            matchContains: "word",
//            scrollHeight: 220
//        });
//    });
//}

$(document).ready(function(){
//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior

		e.preventDefault();

		$('#mask').hide();
		$('.window').hide();

                // Total Message Count Should be updated on Dialog Close

	});

	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});
});

function verifyCredentials(userEmail, userPwd)
{
    $url = "http://"+location.hostname+"/login/index?Email=" + userEmail + "&Password=" + userPwd;

    $("#tdPassword").html('<img style=\'height: 20px;\' src="/images/loading/loading9.gif">');


    $.post($url, {}, function(data) {
        if(data == '1')
        {
            $('#lblErrorWrongPwd').html('');
            window.location.href = "http://"+location.hostname + '/home';
        }
        else
        {
            $('#lblErrorWrongPwd').html('<span class="headerspan redFont">Incorrect Email/Password</span>');
            $("#tdPassword").html('<span class="headerspan">Password:</span>');
        }
    });


    return false;
}

function removeCSSClass(el, cssClassName)
{
  var i, curList, newList;

  if (el.className == null)
    return;

  // Remove the given class name from the element's className property.

  newList = new Array();
  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
    if (curList[i] != cssClassName)
      newList.push(curList[i]);
  el.className = newList.join(" ");
}

function sendPasswordResetEmail(emailAddress, resetUrl)
{
    $url = "http://" + location.hostname + resetUrl + "?email=" + emailAddress;

    if(emailAddress != "")
    {
        $("#tdErrorMessage").html('<img style=\'height: 20px;\' src="/images/loading/loading9.gif">');
        $.post($url, {}, function(data) {
            if(data)
                $("#tdErrorMessage").html('<span></span>');

            $('#mask').fadeOut(100);
            $('.window').hide();
        });
    }
    else
    {
        $("#tdErrorMessage").html('<span class="redFont">Please enter a valid email address</span>');
    }
}

// Fetches the parameter value from URL generated through javascipt
// For-example:  http://rbis.kaust.edu.sa?id=value
function getURLParameter( url )
{
    url = url.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+url+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );

    if( results == null )
        return "";
    else
        return results[1];
}

// Fetches the parameter value from URL generated through Symfony Routing Mechanism
// For-example:  http://rbis.kaust.edu.sa/param1/value1/param2/value2
function getParamValue(urlstring, paramname) {
    var paramvalue = "";
    var splits = urlstring.split('/');
    for (i = 0; i < splits.length; i++) {
        if(splits[i] == paramname) {
            paramvalue = splits[i+1];
        }
    }
    return paramvalue;
}


/// Math Functions to calculat Quartile, Min & Max value from array


function array_firstQuartile(array)
{
var count = array.length;
		var array_tmp = array.sort();
		var n = count*0.25;
		if(Math.ceil(n) == n) return(array_tmp[n-1]+array_tmp[n])/2;
		else return (array_tmp[Math.ceil(n)-1]);
}
function array_median(array)
{
var count = array.length;
		var array_tmp = array.sort();
		var n = count/2;
		if(Math.ceil(n) == n) return(array_tmp[n-1]+array_tmp[n])/2;
		else return (array_tmp[Math.ceil(n)-1]);
}
function array_thirdQuartile(array)
{
var count = array.length;
		var array_tmp = array.sort();
		var n = count*0.75;
		if(Math.ceil(n) == n) return(array_tmp[n-1]+array_tmp[n])/2;
		else return (array_tmp[Math.ceil(n)-1]);
}
function array_max(array){	//get the max. value of an array
        var max = array[0];
        for(var a=0; a<=array.length-1;a++){
                if(array[a] > max){
                        max = array[a];

                }}
        return max;
}

function array_min(array){	//get the min. value of an array
        var min = array[0];
        for(var a=0; a<=array.length-1;a++){
                if(array[a] < min){
                        min = array[a];

                }}
        return min;
}

function loadRBISCommunityMemberList(objTab, param, uid)
{
    

    var lnkAllMembers = document.getElementById('lnkAllMembers');
    var lnkAllProfessors = document.getElementById('lnkAllProfessors');
    var lnkAllCollaborators = document.getElementById('lnkAllCollaborators');

    if(objTab)
    {
        // Remove activeTab CSS class from all tabs first
        removeCSSClass(lnkAllMembers, 'activeTab');
        removeCSSClass(lnkAllProfessors, 'activeTab');
        removeCSSClass(lnkAllCollaborators, 'activeTab');

        // Set activeTab CSS class on current object (tab)
        objTab.className += ' activeTab';
    }



    $url = "http://"+location.hostname+"/general/refreshRBISCommunityList?uType=" + param + "&uid=" + uid;

    $.post($url, {}, function(data) {
        $('#tblRBISCommunity').html( data);
    });


    return false;
}

Date.prototype.getMonthName = function() {
    var m = ['January','February','March','April','May','June','July',
    'August','September','October','November','December'];
    return m[this.getMonth()];
}
Date.prototype.getDayName = function() {
    var d = ['Sunday','Monday','Tuesday','Wednesday',
    'Thursday','Friday','Saturday'];
    return d[this.getDay()];
}

/**
 * Given a date, this function will return human-friendly date time like,
 * "45 minutes ago", "yesterday", or "2 weeks ago""
 * Modified version of http://ejohn.org/blog/javascript-pretty-date/
 */
function prettyDate(time) {
    var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);

    if (isNaN(day_diff) || day_diff < 0)
        return "";

    if (diff < 60) return "just now";
    else if (diff < 3600) {
        var minutes = Math.floor(diff/60);
        if (minutes == 1) return "a minute ago";
        else return  minutes + " minutes ago";
    }
    else if (diff < 86400) {
        var hours = Math.floor(diff/3600);
        if (hours == 1) return "an hour ago";
        return hours + " hours ago";
    }
    else if (diff < 604800) {
        var days = Math.floor(diff/86400);
        if (days == 1) return "yesterday";
//        else return days + " days ago";
        else return date.getDayName();
    }
//    else if (diff < 2592000) {
//        var weeks = Math.floor(diff/604800);
//        if (weeks == 1) return "a week ago";
//        else return  weeks + " weeks ago";
//    }
//    else if (diff < 31536000) {
//        var months = Math.floor(diff/2592000);
//        if (months == 1) return months + " month ago";
//        else return months + " months ago";
//    }
    else if ((new Date()).getFullYear() == date.getFullYear()) {
        return date.getMonthName() + " " + date.getDate();
    }
    else return date.getMonthName() + " " + date.getDate() + ", " + date.getFullYear();
}

/**
 * jQuery implementation of prettyDate above
 */
$.fn.prettyDate = function() {
    return this.each(function(){
        var date = prettyDate(this.title);
        if (date)
            $(this).text(date);
    });
}